#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "TcpConnector.h"
#include "SocketSelector.h"

#pragma comment(lib, "ws2_32.lib")

#ifndef MAKEWORD
#define MAKEWORD(x, y) (x+y)
#endif

using namespace std;
using namespace vs::net;

template<typename STREAM>
void test_connector(int argc, char **argv, STREAM &tcp_stream)
{
	bool connected = false;
	if (argc == 3)
		connected = TcpConnector::Connect("localhost", atoi(argv[2]), tcp_stream);
	else
		connected = TcpConnector::Connect(argv[2], atoi(argv[3]), tcp_stream);
	
	if (connected)
	{
		printf("connect success\n");
	}
	else
	{
		// non-blocking may goes here
		SocketSelector selector;
		//selector.AddReadHandle(tcp_stream);
		selector.AddWriteHandle(tcp_stream);
		struct timeval timeout = {1, 0};
		if (selector.Select(NULL) <= 0)
		{
			printf("select error\n");
			return;
		}
		
		if (selector.IsWritable(tcp_stream))
		{
			printf("asyn connect successed\n");
		}
		else
		{
			printf("connect failed\n");
			return;
		}
	}
	
	char msg[1024] = "";
	char msg_to_server[32] = "MessageToServer";
	int count = atoi(argv[1]);
	for (int i=0; i<count; ++i)
	{
		if (tcp_stream.Send(msg_to_server, strlen(msg_to_server)) > 0)
		{
			printf("have sent message (%s)\n", msg_to_server);
			memset(msg, 0, sizeof(msg));
			if (tcp_stream.Recv(msg, 1024) > 0)
			{
				printf("have received message (%s)\n", msg);
			}
			else
			{
				printf("recv failed\n");
				break;
			}
		}
		else
		{
			printf("send message failed\n");
			break;
		}
	}
}



int main(int argc, char **argv)
{
	if (argc < 3)
	{
		printf("%s count [server] port\n", argv[0]);
		return 0;
	}

	NetInitializer init(MAKEWORD(2, 2));
	if (!init.IsNetworkReady())
	{
		printf("init network error\n");
		return -1;
	}

	/*TcpStream tcp_stream;
	test_connector(argc, argv, tcp_stream);*/

	AsynTcpStream asyn_tcp_stream;
	test_connector(argc, argv, asyn_tcp_stream);

	return 0;
}
